<!--
  退款对话框组件
  @description 支付订单退款功能的对话框组件
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <Dialog v-model="dialogVisible" :title="t('settle.payment.refund')" width="600px">
    <div v-loading="loading">
      <!-- 支付信息展示 -->
      <el-descriptions :column="2" border class="mb-20px" v-if="paymentData">
        <el-descriptions-item :label="t('settle.payment.orderNo')">
          {{ paymentData.orderNo }}
        </el-descriptions-item>
        <el-descriptions-item :label="t('settle.payment.merchantName')">
          {{ paymentData.merchantName }}
        </el-descriptions-item>
        <el-descriptions-item :label="t('settle.payment.paymentAmount')">
          <span class="amount-text">¥{{ (paymentData.paymentAmount / 100).toFixed(2) }}</span>
        </el-descriptions-item>
        <el-descriptions-item :label="t('settle.payment.channelType')">
          <el-tag :type="getChannelTypeTagType(paymentData.channelType)">
            {{ channelTypeOptions[paymentData.channelType] }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item :label="t('settle.payment.paymentTime')" :span="2">
          {{ formatDate(paymentData.paymentTime) }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 退款表单 -->
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <el-form-item :label="t('settle.payment.refundAmount')" prop="refundAmount">
          <el-input-number
            v-model="formData.refundAmount"
            :placeholder="t('settle.payment.rules.refundAmountRequired')"
            :min="0.01"
            :max="maxRefundAmount"
            :precision="2"
            :step="0.01"
            style="width: 100%"
          />
          <div class="form-tip">
            {{ t('settle.payment.maxRefundAmount') }}: ¥{{ maxRefundAmount.toFixed(2) }}
          </div>
        </el-form-item>

        <el-form-item :label="t('settle.payment.refundReason')" prop="refundReason">
          <el-select
            v-model="formData.refundReason"
            :placeholder="t('settle.payment.rules.refundReasonRequired')"
            style="width: 100%"
          >
            <el-option
              v-for="(label, value) in refundReasonOptions"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>

        <el-form-item :label="t('settle.payment.refundDesc')" prop="refundDesc">
          <el-input
            v-model="formData.refundDesc"
            type="textarea"
            :placeholder="t('settle.common.pleaseInput') + t('settle.payment.refundDesc')"
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="loading">
        {{ t('settle.common.confirm') }}
      </el-button>
      <el-button @click="dialogVisible = false">
        {{ t('settle.common.cancel') }}
      </el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { formatDate } from '@/utils/formatTime'
import { createPaymentRefundApi } from '@/api/settle/payment'
import type { PaymentVO, RefundPaymentReqVO } from '@/api/settle/types'
import { ChannelTypeEnum } from '@/api/settle/types'
import { Dialog } from '@/components/Dialog'

defineOptions({ name: 'RefundDialog' })

const { t } = useI18n()

// 弹窗相关
const dialogVisible = ref(false)
const loading = ref(false)

// 支付数据
const paymentData = ref<PaymentVO>()

// 表单相关
const formRef = ref<FormInstance>()
const formData = ref<RefundPaymentReqVO>({
  paymentId: 0,
  refundAmount: 0,
  refundReason: '',
  refundDesc: ''
})

// 选项数据
const channelTypeOptions = {
  [ChannelTypeEnum.WECHAT]: t('settle.payment.channelTypes.wechat'),
  [ChannelTypeEnum.ALIPAY]: t('settle.payment.channelTypes.alipay'),
  [ChannelTypeEnum.UNIONPAY]: t('settle.payment.channelTypes.unionpay'),
  [ChannelTypeEnum.DIGITAL_RMB]: t('settle.payment.channelTypes.digitalRmb')
}

const refundReasonOptions = {
  USER_CANCEL: t('settle.payment.refundReasons.userCancel'),
  MERCHANT_CANCEL: t('settle.payment.refundReasons.merchantCancel'),
  SYSTEM_ERROR: t('settle.payment.refundReasons.systemError'),
  DUPLICATE_PAYMENT: t('settle.payment.refundReasons.duplicatePayment'),
  OTHER: t('settle.payment.refundReasons.other')
}

// 计算属性
const maxRefundAmount = computed(() => {
  if (!paymentData.value) return 0
  const refundedAmount = paymentData.value.refundAmount || 0
  return (paymentData.value.paymentAmount - refundedAmount) / 100
})

// 表单校验规则
const formRules = reactive<FormRules>({
  refundAmount: [
    { required: true, message: t('settle.payment.rules.refundAmountRequired'), trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error(t('settle.payment.rules.refundAmountMin')))
        } else if (value > maxRefundAmount.value) {
          callback(new Error(t('settle.payment.rules.refundAmountMax')))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  refundReason: [
    { required: true, message: t('settle.payment.rules.refundReasonRequired'), trigger: 'change' }
  ]
})

// 事件定义
const emit = defineEmits(['success'])

/**
 * 打开对话框
 */
const open = (payment: PaymentVO) => {
  dialogVisible.value = true
  paymentData.value = payment
  resetForm()
  formData.value.paymentId = payment.id
  formData.value.refundAmount = maxRefundAmount.value
}

/**
 * 提交退款
 */
const submitForm = async () => {
  const valid = await formRef.value?.validate()
  if (!valid) return

  loading.value = true
  try {
    const data = { ...formData.value }
    // 将元转换为分
    data.refundAmount = Math.round(data.refundAmount * 100)

    await createPaymentRefundApi(data)
    ElMessage.success(t('settle.payment.tips.refundSuccess'))
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('退款失败:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 重置表单
 */
const resetForm = () => {
  formData.value = {
    paymentId: 0,
    refundAmount: 0,
    refundReason: '',
    refundDesc: ''
  }
  formRef.value?.resetFields()
}

// 标签类型获取函数
const getChannelTypeTagType = (type: number) => {
  const typeMap = {
    [ChannelTypeEnum.WECHAT]: 'success',
    [ChannelTypeEnum.ALIPAY]: 'primary',
    [ChannelTypeEnum.UNIONPAY]: 'warning',
    [ChannelTypeEnum.DIGITAL_RMB]: 'info'
  }
  return typeMap[type] || ''
}

// 暴露方法
defineExpose({ open })
</script>

<style scoped>
.mb-20px {
  margin-bottom: 20px;
}

.amount-text {
  color: #409eff;
  font-weight: bold;
  font-size: 16px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>
